<!--
 * @Descripttion: 
 * @version: 
 * @Author: Jun
 * @Date: 2021-06-09 11:09:37
 * @LastEditors: Jun
 * @LastEditTime: 2021-06-10 14:42:42
-->
<template>
  <div class="pay">
    <div class="pay-content">
      <div class="qrcode" id="qrcode"></div>
      <div class="pay-text">
        <p>请使用微信“扫一扫”</p>
        <p>扫描二维码支付</p>
      </div>
    </div>
  </div>
</template>

<script>
import { url } from "api/wxPay.js";
import {pcCheckPayUrl} from "api/pcCheckPay.js"
import QRCode from "qrcodejs2"; //引入生成二维码方法

export default {
  props: {
    id: {
      //考试id
      type: String,
      required: true,
    },
  },
  data() {
    return {
      timer: "",//定时器
    };
  },
  methods: {
    API_wxPay(id) {
      //支付接口
      return this.$httpRequest({
        url: url,
        method: "POST",
        data: {
          param: {
            id: id, //考试id
            app: 2, //1-小程序微信支付，2-pc微信支付
          },
        },
      });
    },
    async API_pcCheckPay(id) {
      //微信支付查询
      return this.$httpRequest({
        url: pcCheckPayUrl,
        method: "POST",
        data: {
          param: {
            id: id,
          },
        },
      });
    },
    createCode(url) {
      //根据codeUrl生成微信二维码
      new QRCode(document.getElementById("qrcode"), url);
    },
    timeHandler() {
      //定时器-用于监听是否支付成功
      //微信支付完毕之后没有返回响应的状态，所以需要使用定时器监听用户是否有支付成功
      this.timer = setInterval(async () => {
        let res = await this.API_pcCheckPay(this.id);
        console.log(res);
        if (res.data.code === 1000) {
          this.$message({
            message: res.data.msg,
            type: "success",
          });
          this.$router.replace("/signUpList"); //重定向回我的报名列表页
        }
      }, 3000);
    },
  },
  async created() {
    let res = await this.API_wxPay(this.id);//调用微信支付接口
    this.createCode(res.data.data.codeUrl);//显示微信支付二维码

    clearInterval(this.timer); //进入页面先清空计时器再开始计时
    this.timeHandler();
  },
  beforeDestroy() {
    clearInterval(this.timer); //离开的时候要清空计时器
    this.timer = null;
  },
};
</script>

<style lang="scss" scoped>
@import "style/views/pay.scss"
</style>